<script setup>
import { Message, MessageBox } from 'element-ui';
import dayjs from 'dayjs';
import { getMtProInfo, submitMtProject, getType, getProjectHistory } from '@/api/index.js';
import { useRequest, useWatch } from '@/hooks';
import { rulesPattern } from '@/utils/tools';
import { TableList } from '@/components/MainComponents.js';

const props = defineProps({
  enterprise: { type: Object, default: () => null },
});
const emit = defineEmits(['projectData']);
const Forms = ref(null);
const projectCode = ref('');
const queryParams = ref({
  startDate: null,
  endDate: null,
  type: null,
  energyType: null,
});
const typeList = ref([]);
const open = ref(false);
const pageObj = ref({
  pageSize: 10,
  pageNum: 1,
});

const columObj = ref({
  columnData: [
    {
      slotName: 'jcnx',
      label: '监测年限',
    },
    {
      text: true,
      prop: 'energyType',
      label: '监测能源类型',
    },
    {
      text: true,
      prop: 'contractAmount',
      label: '投资总额（元）',
    },
    {
      text: true,
      prop: 'createTime',
      label: '修改时间',
    },
    {
      text: true,
      prop: 'createBy',
      label: '修改人',
    },
  ],
});
useRequest(getType, {
  onSuccess: res => {
    typeList.value = res;
  },
});
const [, , run] = useRequest(getMtProInfo, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      if (res?.data?.projectCode) {
        emit('projectData', res?.data?.projectCode);
      }
      projectCode.value = res?.data?.projectCode;
      queryParams.value = {
        ...res.data,
      };
      queryParams.value.energyType = res.data?.energyType?.map(Number);
      if (res.data?.endDate === '长期') {
        queryParams.value.type = '长期';
        queryParams.value.endDate = null;
      } else if (res.data?.endDate?.length > 0) {
        queryParams.value.type = '具体时间';
        queryParams.value.endDate = res.data?.endDate;
      } else if (!res.data?.endDate) {
        // queryParams.value.type = null;
      }
    }
  },
});
const [, , submitRun] = useRequest(submitMtProject, {
  manual: true,
  onSuccess: res => {
    if (res.msg === '操作成功') {
      Message.success(res.msg);
      run({ enterpriseCode: props.enterprise?.enterpriseCode, projectType: 'JC' });
      emit('projectData');
    }
  },
});
const [historyList, loading2, historyRun] = useRequest(getProjectHistory, {
  manual: true,
});
// 开始时间不能大于结束时间
const pickerOptsStart = ref({
  disabledDate: time => {
    if (queryParams.value.endDate) {
      return dayjs(time) > dayjs(queryParams.value.endDate);
    }
  },
});
// 结束时间不能小于开始时间
const pickerOpts = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(queryParams.value.startDate);
  },
});
const handleSave = () => {
  Forms.value.validate(valid => {
    if (valid) {
      let obj = {
        startDate: queryParams.value.startDate,
        endDate: queryParams.value.type === '长期' ? '长期' : queryParams.value.endDate,
        energyType: queryParams.value.energyType.toString(),
        amount: queryParams.value.amount,
      };
      MessageBox.confirm('请确认信息无误', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      }).then(() => {
        submitRun({ enterpriseCode: props.enterprise?.enterpriseCode, project: obj, projectCode: projectCode.value });
      });
    } else {
      return false;
    }
  });
};
const showHistory = () => {
  open.value = true;
  historyRun({ enterpriseCode: props.enterprise?.enterpriseCode, projectCode: projectCode.value });
};
const getList = e => {
  pageObj.value.pageNum = e.page;
  pageObj.value.pageSize = e.limit;
  historyRun({ enterpriseCode: props.enterprise?.enterpriseCode, ...pageObj.value });
};
const changeType = val => {
  // queryParams.value.type = val;
  if (val === '长期') {
    queryParams.value.endDate = null;
  } else {
    queryParams.value.endDate = '';
  }
  Forms.value.validateField('type');
};
useWatch(
  () => props.enterprise,
  n => {
    if (n) {
      run({ enterpriseCode: n?.enterpriseCode, projectType: 'JC' });
    }
  },
  { deep: true, immediate: true },
);
</script>
<template>
  <div>
    <el-form :model="queryParams" ref="Forms" size="small" label-width="150px" class="u-mt20" :inline="true">
      <el-form-item
        label="监测服务年限："
        :rules="{ required: true, message: '请选择', trigger: ['change'] }"
        style="margin-bottom: 0"
      >
        <el-form-item
          prop="startDate"
          :rules="{ required: true, message: '请选择开始时间', trigger: ['change'] }"
          style="margin-right: 10px !important"
        >
          <el-date-picker
            style="width: 160px"
            v-model="queryParams.startDate"
            type="date"
            :picker-options="pickerOptsStart"
            value-format="yyyy-MM-dd"
            placeholder="请选择开始时间"
          ></el-date-picker>
        </el-form-item>
        -
        <el-form-item
          prop="type"
          :rules="{ required: true, message: '请选择时间', trigger: ['change', 'blur'] }"
          style="margin-left: 10px"
        >
          <el-select v-model="queryParams.type" class="u-mr10" style="width: 120px" @change="changeType">
            <el-option value="具体时间">具体时间</el-option>
            <el-option value="长期">长期</el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-show="queryParams.type === '具体时间'"
          prop="endDate"
          :rules="{
            required: queryParams.type === '具体时间' ? true : false,
            message: '请选择截止时间',
            trigger: ['change', 'blur'],
          }"
        >
          <el-date-picker
            style="width: 160px"
            v-model="queryParams.endDate"
            type="date"
            :picker-options="pickerOpts"
            value-format="yyyy-MM-dd"
            placeholder="请选择截止时间"
          ></el-date-picker>
        </el-form-item>
        <a class="u-primary u-ml10" @click="showHistory">修改记录</a>
        <div class="red">*记录运营开始结束时间</div>
      </el-form-item>
      <br />
      <el-form-item
        label="托管能源类型："
        prop="energyType"
        :rules="{ required: true, message: '请选择监测能源类型', trigger: ['change'] }"
      >
        <el-select v-model="queryParams.energyType" multiple placeholder="请选择监测能源类型" style="width: 600px">
          <el-option v-for="item in typeList" :key="item.id" :label="item.energyName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <br />
      <el-form-item
        label="投资总额（元）："
        prop="amount"
        :rules="[
          {
            pattern: rulesPattern.remainder2,
            message: '请输入小数点后2位正数',
            trigger: 'blur',
          },
        ]"
      >
        <el-input
          style="width: 600px"
          placeholder="请输入合同金额"
          v-filter-input
          v-model="queryParams.amount"
          clearable
          size="small"
        />
      </el-form-item>
      <br />
      <el-form-item style="margin-left: 20px">
        <el-button size="small" type="primary" @click="handleSave">提交</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="修改记录" :visible.sync="open" width="60%" :before-close="() => (open = false)" append-to-body>
      <TableList
        v-loading="loading2"
        :total="historyList?.total ?? 0"
        :tableData="historyList?.rows"
        :pageObj="pageObj"
        :columObj="columObj"
        @getList="getList"
      >
        <template v-slot:jcnx="{ scope }">{{ scope.row.startTime }}-{{ scope.row.endTimeStr }}</template>
      </TableList>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.red {
  color: #ff0000;
}
</style>
